import GlobalStore from '../../global.store';
import fetch from '../../common/fetch';
import {observable, action, runInAction, useStrict} from 'mobx';
useStrict(true);

const api = {
  userList: '/api/user/list',
  userDelete: '/api/user/del',
  userEdit: '/api/user/edit'
};

export default class UserStore extends GlobalStore{
  @observable defaultPage = 1;
  @observable defaultSize = 10;
  @observable total = 0;
  @observable page = 1;
  @observable size = 10;
  @observable list = [];
  @observable editFormVisible = false;
  @observable editUser = {};
  @observable editState = 'add';
  @observable searchParams = {};
  @observable isSearch = false;

  // 查询列表
  @action getList = async (page, size) => {
    this.openLoading();
    this.page = page || this.defaultPage;
    this.size = size || this.defaultSize;
    let params = {page: this.page, size: this.size};
    if(this.isSearch) {
      params.search = this.searchParams;
    }
    let data = await fetch.post(api.userList, params);
    runInAction(() => {
      this.loading = false;
      this.total = data.total;
      this.list = data.list;
    });
  };

  // 删除用户
  @action del = async (keys) => {
    this.openLoading();
    await fetch.delete(api.userDelete, {data: keys});
    runInAction(() => {
      this.loading = false;
      this.getList(this.page, this.size);
    });
  }

  // 显示编辑框
  @action showEdit = () => {
    this.editFormVisible = true;
  }

  // 隐藏编辑框
  @action hideEdit = () => {
    this.editFormVisible = false;
  }

  // 设置当前编辑的用户
  @action setEditUser = (user) => {
    this.editUser = user || {};
    this.editState = user ? 'edit' : 'add';
  }

  // 编辑内容
  @action edit = async (user) => {
    this.openLoading();
    switch(this.editState) {
      case 'add':
        await fetch.post(api.userEdit, user);
        break;
      case 'edit':
        user.id = this.editUser.id;
        await fetch.post(api.userEdit, user);
        break;
      default:
        return;
    }
    runInAction(() => {
      this.loading = false;
      // this.setEditUser();
      this.getList(this.page, this.size);
    });
  }

  // 搜索内容
  @action search = async (params) => {
    this.searchParams = params;
    this.isSearch = Object.keys(params).length !== 0;
    this.getList();
  }
}